package com.example.nfc.base;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.util.Log;

import com.example.nfc.server.APIAction;
import com.example.nfc.server.network.async.AsyncTaskManager;
import com.example.nfc.server.network.async.OnDataListener;
import com.example.nfc.server.network.http.HttpException;
import com.example.nfc.server.utils.CommonUtils;
import com.example.nfc.server.utils.FileUtil;
import com.example.nfc.server.utils.NToast;
import com.example.nfc.server.utils.SharedPreferencesUtil;
import com.example.nfc.server.utils.json.JsonMananger;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


public class BaseNfcActivity extends AppCompatActivity  implements OnDataListener {
    protected NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;

    protected Context mContext;
    public AsyncTaskManager mAsyncTaskManager;
    protected APIAction action;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();

        //异步线程、事件相关
        mAsyncTaskManager = AsyncTaskManager.getInstance(mContext);
        // API接口
        action = new APIAction(mContext);
    }

    /**
     * 发送请求（需要检查网络）
     *
     * @param requestCode 请求码
     */
    public void request(int requestCode) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(requestCode, this);
        }
    }


    /**
     * 发送请求（需要检查网络）
     *
     * @param id 请求数据的用户ID或者groupID
     * @param requestCode 请求码
     */
    public void request(String id , int requestCode) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(id, requestCode, this);
        }
    }

    /**
     * 发起请求 并把Uri转为path
     * @param uri
     * @param requestCode
     */
    public void request(Uri uri, int requestCode){
        String filepath = FileUtil.getPath(mContext,uri);
        request(filepath,requestCode);
    }

    /**
     * 发送请求
     *
     * @param requestCode    请求码
     * @param isCheckNetwork 是否需检查网络，true检查，false不检查
     */
    public void request(int requestCode, boolean isCheckNetwork) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(requestCode, isCheckNetwork, this);
        }
    }

    /**
     * 取消所有请求
     */
    public void cancelRequest() {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.cancelRequest();
        }
    }

    /**
     * onCreat->onStart->onResume->onPause->onStop->onDestroy
     * 启动Activity，界面可见时.
     */
    @Override
    protected void onStart() {
        super.onStart();
        //此处adapter需要重新获取，否则无法获取message
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        //一旦截获NFC消息，就会通过PendingIntent调用窗口
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
    }

    /**
     * 获得焦点，按钮可以点击
     */
    @Override
    public void onResume() {
        super.onResume();
        //设置处理优于所有其他NFC的处理
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
    }

    /**
     * 打开并关闭当前
     * @param cla
     * @param obj
     */
    public void startActivityAndFinish(Class cla,Object ...obj){
        startActivity(cla,obj);
        finish();
    }
    /**
     * 打开页面
     * @param cla
     * @param obj 参数名称ext_{i},intentKV 只能传int float String
     */
    public void startActivity(Class cla,Object ...obj){
        //防止点击太快打开多个页面
        Intent intent = CommonUtils.getIntent(obj);
        intent.setClass(this,cla);
        this.startActivity(intent);
    }

    /**
     * 打开有回调的页面
     * @param cla
     * @param requestCode
     * @param obj 参数名称ext_{i},intentKV 只能传int float String
     */
    public void startActivityWidthResult(Class cla, int requestCode, Object ...obj){
        Intent intent = CommonUtils.getIntent(obj);
        intent.setClass(this,cla);
        startActivityForResult(intent,requestCode);
    }

    /**
     * 暂停Activity，界面获取焦点，按钮可以点击
     */
    @Override
    public void onPause() {
        super.onPause();
        //恢复默认状态
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    public Object doInBackground(int requestCode, String parameter) throws HttpException {
        return null;
    }

    @Override
    public void onSuccess(int requestCode, Object result) {

    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (state) {
            case AsyncTaskManager.REQUEST_CREATE_CODE:
                shortToast( "创建成功");
                break;
            case AsyncTaskManager.REQUEST_DATA_ERROR_CODE:
                shortToast( "提交数据不合法,请检查");
                break;
            case AsyncTaskManager.REQUEST_FORBIDDEN_CODE:
                shortToast( "无权限访问");
                break;
            case AsyncTaskManager.REQUEST_NOTPAGE_CODE:
                shortToast( "当前API接口已失效");
                break;
            case AsyncTaskManager.REQUEST_DECODE_CODE:
                shortToast( "数据解析异常！");
                break;
            case AsyncTaskManager.HTTP_TIMEOUT_CODE:
                shortToast( "网络请求超时，请重试!");
                break;
            case AsyncTaskManager.REQUEST_ERROR_CODE:
                shortToast( "网络请求异常，请重试！");
                break;
            case AsyncTaskManager.RESPONE_ERROR_CODE:
                shortToast( "很抱歉当前服务器故障，请稍后重试！");
                break;
            case AsyncTaskManager.HTTP_ERROR_CODE:
                shortToast( "网络请求异常，请重试!");
                break;
            case AsyncTaskManager.HTTP_NULL_CODE:
                shortToast( "当前网络不可用");
                break;
        }
    }

    /**
     * 简单存取数据
     * @param key
     * @param value
     * @return
     */
    public boolean putData(String key,Object value){
        return SharedPreferencesUtil.putData(key,value);
    }
    public <T>T getData(String key,Object value){
        return (T)SharedPreferencesUtil.getData(key,value);
    }

    /**
     * 提示
     * @param msg
     */
    public void shortToast(String msg){
        NToast.shortToast(mContext,msg);
    }

    public void longToast(String msg){
        NToast.longToast(mContext,msg);
    }

    /**
     *
     * @param json
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> cls) {
        try {
            return JsonMananger.jsonToBean(json,cls);
        }catch (Exception e){
            Log.e("jsonToBean",e.getMessage());
        }
        return null;
    }

    /**
     *
     * @param obj
     * @return
     * @throws HttpException
     */
    public static String beanToJson(Object obj){
        try {
            return JsonMananger.beanToJson(obj);
        }catch (Exception e){
            Log.e("beanToJson",e.getMessage());
        }
        return null;
    }
}

